package lab10;

import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.concurrent.Semaphore;

public class HttpServer extends Thread
{
	private ServerSocket socket;
	private int maxConnections = 50;
	private Semaphore sem;
	private byte[] favicon;
	
	public HttpServer() throws IOException
	{
		socket = new ServerSocket(80);
		sem = new Semaphore(maxConnections);
		File icon = new File("./src/favicon.ico");
		favicon = this.readFile(icon);
	}
	
	public byte[] readFile(File file) throws IOException
	{
		ByteBuffer buffer = ByteBuffer.allocate((int)file.length());
		buffer.clear();

			FileInputStream fileReader = new FileInputStream(file);
			fileReader.read(buffer.array());
			fileReader.close();

		return buffer.array();
	}
	
	public void connectionReleased ()
	{
		sem.release();
		System.out.println("available permits: "+sem.availablePermits());
		System.out.println("closed a connection");
	}

	synchronized public byte[] getFavicon()
	{
		return favicon;
	}
	
	public void run ()
	{
		while (true)
		{
			try
			{
				System.out.println("available permits: "+sem.availablePermits());
				sem.acquire(1);
				Socket connection = socket.accept();
				RequestWorker worker = new RequestWorker(connection, this);
				worker.run();
			} 
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
